package com.oe.market.modules.cq.service;

import cn.hutool.http.HttpUtil;
import com.oe.market.modules.base.model.bean.ServerInfo;
import okhttp3.*;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CQMessageAnalyzeService {

    public static CQMessageAnalyzeService me = new CQMessageAnalyzeService();

    public String analyze(String msg) {
        String[] e = msg.split("饿了么");
        if (e.length != 0) {
            String regex = "url=[htps]+://[url.cn/]+[0-9a-zA-Z]{0,10}";
            Pattern pt=Pattern.compile(regex);
            Matcher mt = pt.matcher(msg);
            if (mt.find()) {

                return eleUrl(mt.group().substring(4));
            }
        }
        return null;
    }

    protected String eleUrl(String url) {
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .build();
        final Call call = okHttpClient.newCall(request);
        try {
            Response response = call.execute().networkResponse();

            String json = "{\"url\":\""+ response.request().url() +"\"}";
            final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            RequestBody body = RequestBody.create(JSON, json);
            Request request1 = new Request.Builder()
                    .url(ServerInfo.url + "/v1/ele/package/add")
                    .addHeader("cookie","user=robot;current_sign=2023fadf4085d6dba4433301521da8be0c69dac2df74599ccb9b1d8d9967a693")
                    .post(body)
                    .build();

            Response response1 = okHttpClient.newCall(request1).execute();
            return  response1.body().string();


        } catch (IOException ignored) {
        }
        return null;
    }


    public static void main(String[] args) {

//        String str = "[CQ:rich,text= 饿了么拼手气，第10个领取的人得大红包 最高10元大红包，饿了么拼手气@你,url=https://url.cn/507wdt7]";

//        String regex = "url=[htps]+://[url.cn/]+[0-9a-zA-Z]{0,10}";
//        String rex = "[htps]+";

//        Pattern pt=Pattern.compile(regex);
//        Matcher mt = pt.matcher(str);
//        mt.find();
//        mt.group();
//        System.out.println(mt.group().substring(4));
//        System.out.println(mt.group().substring(4));

        System.out.println(CQMessageAnalyzeService.me.analyze("[CQ:rich,text=\n" +
                " 饿了么拼手气，第10个领取的人得大红包 最高10元大红包，饿了么拼手气@你 \n" +
                ",url=https://url.cn/5hR5ZIs]"));


    }
}
